import { DialogResult } from "./enums";

let zIndex = 200;
let maskZIndexes: number[] = [];
let maskId = "div_$mask$_unique_r_t_q_A";
let dialogs: any[] = [];
const tool = {
    isMaskShowed: function () {
        let div = document.getElementById(maskId);
        return div && div.style.display == "";
    },
    showMask: function () {
        let div = document.getElementById(maskId);
        if (!div) {
            div = document.createElement("div");
            div.setAttribute("id", maskId);
            div.style.position = "absolute";
            div.style.height = "100%";
            div.style.width = "100%";
            div.style.top = "0px";
            div.style.left = "0px";
            div.style.opacity = "0.2";
            div.style.backgroundColor = "var(--color-light-2)";
            document.body.appendChild(div);
        }
        let curZIndex = tool.increaseZIndex(1);
        maskZIndexes.push(curZIndex);
        div.style.zIndex = curZIndex.toString();
        div.style.display = "";
    },
    hideMask: function () {
        let div = document.getElementById("div_$mask$_unique_r_t_q_A");
        if (!div) {
            return;
        }
        if (maskZIndexes.length == 0) {
            div.style.display = "none";
            return;
        }
        let result = maskZIndexes.splice(maskZIndexes.length - 1, 1);
        if (maskZIndexes.length == 0) {
            div.style.display = "none";
            return;
        }
        div.style.zIndex = result[0].toString()
    },
    increaseZIndex: function (step: number) {
        zIndex += step;
        return zIndex;
    },
    minusZIndex: function (step: number) {
        zIndex -= step;
        return zIndex;
    },
    createDragMask: (): HTMLDivElement => {
        let mask = document.createElement("div");
        mask.style.position = "absolute";
        mask.style.left = "0px";
        mask.style.top = "0px";
        mask.style.width = "100%";
        mask.style.height = "100%";
        mask.style.backgroundColor = "transparent";
        return mask;
    },
    closeCurrentDialog: () => {
        if (dialogs.length == 0) {
            return;
        }
        for (let i = dialogs.length - 1; i >= 0; i--) {
            if (dialogs[i].setupState.data.isVisible) {
                dialogs[i].exposed.close(DialogResult.CloseWindow);
                break;
            }
        }
    },
    setCurrentDialog: (dialogInstance: any) => {
        dialogs.push(dialogInstance);
    },
    removeDialog: (dialogInstance: any) => {
        for (let i = 0; i < dialogs.length; i++) {
            if (dialogs[i] == dialogInstance) {
                dialogs.splice(i, 1);
                break;
            }
        }
    }
};

export default tool;